# $Id: CmdParse.pm 6 2008-06-16 18:04:51Z longerdev $
=head1 COPYRIGHT

Copyright (C) 2008 Longer <longerdev@gmail.com>

=head1 LICENSE

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

=cut

package RL::CmdParse;

use strict;
use Data::Dumper;

sub new{
	my $self = {};
	$self->{'key_mask'}  = $_[1];
	#die Dumper($self->{'key_mask'});
	return bless $self;
}

sub get{
	my $self = shift;
	my $key = shift;	
	
	return $self->{'keys'}{$key};
}

sub exist{
	my $self = shift;
	my $key = shift;
	
	return defined($self->{'keys'}{$key});
}

sub haveval{
	my $self = shift;
	my $key = shift;
	
	foreach (keys %{$self->{'key_mask'}}){
		if ($_ eq $key){
			return $self->{'key_mask'}{$key};
		}
	}
	return 0;
}

sub getsz{
	my $self = shift;
	my $key = shift;
	my $a = $self->{'keys'}{$key};
	#die Dumper($a);
	my $sz = 0;
	foreach (@$a){
		$sz++;
	}
	return $sz;
# 	return $#a;
}

sub can{
	my $self = shift;
	my $key = shift;
	
	return 1 if $key eq 'none';
	
	if ($self->getsz($key)<$self->haveval($key) || $self->haveval($key) == -1){
		return 1;
	}
	return 0;
}

sub parse{
	my $self = shift;
	
	my $curkey = "none";
	my $ci = 0;
	
	foreach (@ARGV){
		if ($_ =~ /^--([A-Za-z0-9]+)/){
			#$keys{$1} =
			#$curkey = $1;
			$curkey = $self->can($1)?$1:'none';
			if ($_ =~ /=/){
				$_ =~ m/^--[A-Za-z0-9]+=(.+)/;
				my $st = $1;
				$st =~ s/^"|"$//;
				$self->{'keys'}{$curkey} = [$st];
			}
			else{
				$self->{'keys'}{$curkey} = [];
			}
			$ci = 0;
		}
		elsif ($_ =~ /^-([A-Za-z0-9]+)/){
			$curkey = $1;
			#$curkey = can($1)?$1:'none';
			if (length($curkey)>1){
				for (my $i=0;$i<length($curkey);$i++){
					$self->{'keys'}{substr($curkey,$i,1)} = [];
				}
				$curkey = substr($curkey,length($curkey)-1,1);
				$curkey = $self->can($curkey)?$curkey:'none';
			}
			else{
				$self->{'keys'}{$curkey} = [];
			}
			$ci=0;
		}
		else{
			#push [%keys->{$curkey}], [$_];
			$curkey = $self->can($curkey)?$curkey:'none';
			$self->{'keys'}{$curkey}[$ci] = $_;
			$ci++;
		}
	}
}

1;